<?php


namespace App\Models\CacheModel;


use app\common\lib\exception\ApiException;
use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class ZlUserLoginRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_user_login_record';

    protected $cacheModel = 'user.login_record';

    protected $cacheIdKey = 'id';

    /**
     * 写入登陆日志
     * @param array $data
     *  $data = [
     *      'uid' => $uid,
     *      'status' => $status,     1=>正常 0=>删除 2=>开关关闭记录数据
     *      'mobile_type' => '',
     *      'login_type' => $loginType,  登录方式 1=>微信，2=>qq,3=>微博 4=>手机号  5=>苹果登陆 6=>手机号一键登录
     *      'version' => '',
     *      'login_ip' => $ip,
     *      'create_time' => time()
     *  ];
     * @return bool
     */
    public function saveData(array $data): bool
    {
        try
        {
            $this->allowField(true)->save($data);

            if ($data['status'] === 1)
            {
                $this->listDataAdd($data['uid'], [$this->id => $this->id]);
            }
        }
        catch (\Exception $e)
        {
            Log::write('用户登陆日志写入失败：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }
        return true;
    }

    /**
     * 删除登陆记录
     * @param int $uid
     * @param int $id
     * @return bool
     */
    public function recordDel(int $uid, int $id)
    {
        try
        {
            $this->save(['status' => 0], ['id' => $id]);

            $this->listDataDel($uid, [$id]);
        }
        catch (\Exception $e)
        {
            Log::write('用户登陆日志删除失败：' . $e->getMessage() . "；错误文件「{$e->getFile()}」错误行数「{$e->getLine()}」", 'error', true);
            return false;
        }

        return true;
    }

    /**
     * 获取用户登陆记录
     * @param $uid
     * @return array
     * @throws \Exception
     */
    public function getRecordList($uid): array
    {
        $ids = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setSort('DESC')->ZsGetIocData('list', function () use ($uid)
        {
            try
            {
                $ids = $this->where(['uid' => $uid, 'status' => 1])->order('id desc')->column('id');
                $data = [];
                foreach ($ids as $idItem)
                {
                    $data[$idItem] = $idItem;
                }
            }
            catch (\Exception $e)
            {
                $data = [];
            }
            return $data;
        });

        $infoDatas = $this->batchGetInfoByIds($ids, ['id', 'mobile_type', 'create_time']);

        $resData = [];
        foreach ($ids as $id)
        {
            if (!isset($infoDatas[$id]))
            {
                continue;
            }

            $resData[] = [
                'id' => (int)$id,
                'mobile' => $infoDatas[$id]['mobile_type'] ?? '',
                'login_time' => '最近登录时间：' . date('Y.m.d H:i', $infoDatas[$id]['create_time'] ?? 0),
            ];
        }

        return $resData;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);

            } else
            {
                $this->where(['uid' => $type[0], 'status' => 1])->order('id ' . $sortType);
            }

            $data = $this->column('uid,mobile_type,status,login_type,version,login_ip,create_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }
}
